package com.yungu.swift.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

    private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);
    private final static String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private final static int KEY_LENGTH = 16;
    /**
     * 开发默认key
     */
    public final static String DEFAULT_KEY = "1234567812345678";

    /**
     * 加密
     */
    public static String encryptAES(String content, String key) throws Exception {
        if (key == null) {
            logger.info("Key is null, content:{}", content);
            return null;
        }
        //判断Key是否为16位
        if (key.length() != KEY_LENGTH) {
            logger.info("key's length is error.key:{}", key);
            return null;
        }
        byte[] raw = key.getBytes("UTF-8");
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
        //"算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(key.getBytes("UTF-8"));
        //此处使用BASE64做转码功能，同时能起到2次加密的作用。
        return Base64Utils.encode(encrypted);
    }

    /**
     * 解密
     */
    public static String decryptAES(String content, String key) {
        try {
            if (key == null) {
                logger.info("Key is null, content:{}", content);
                return null;
            }
            //判断Key是否为16位
            if (key.length() != KEY_LENGTH) {
                logger.info("key's length is error.key:{}", key);
                return null;
            }
            byte[] raw = key.getBytes("UTF-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            //先用base64解密
            byte[] decode = Base64Utils.decode(content);
            byte[] original = cipher.doFinal(decode);
            return new String(original, "UTF-8");
        } catch (Exception e) {
            return null;
        }
    }

}